package com.dubito.web;

import java.io.IOException;
import java.sql.Connection;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.dubito.dao.AuthDao;
import com.dubito.dao.RoleDao;
import com.dubito.model.User;
import com.dubito.util.DbUtil;
import com.dubito.util.ResponseUtil;

import net.sf.json.JSONArray;

public class AuthServlet extends HttpServlet{

	
	private static final long serialVersionUID = 1L;
	
	DbUtil db = new DbUtil();
	AuthDao authDao = new AuthDao();
	RoleDao roleDao = new RoleDao();
	
	@Override
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		this.doPost(request, response);
	}

	@Override
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		request.setCharacterEncoding("utf-8");
		String action = request.getParameter("action");
		if("menu".equals(action)){
			this.menuActoin(request, response);
		}
	}
	
	private void menuActoin(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		
		String parentId = request.getParameter("parentId");
		Connection con = null;
		try {
			con = db.getCon();
			User user = (User) request.getSession().getAttribute("currentUser");
			String authIds = roleDao.getAuthIdsById(con,user.getRoleId());
			JSONArray jsonArray = authDao.getAuthsByParentId(con, parentId,authIds);
			ResponseUtil.write(response, jsonArray);
		} catch (Exception e) {
			e.printStackTrace();
		}finally {
			try {
				db.closeCon(con);
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
	}

}
